package com.cctv.iseemini.controller;

import com.cctv.iseemini.pojo.User;
import com.cctv.iseemini.service.UserService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.validation.Valid;

/**
 * @author cctv 2019-02-14
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {
    @Autowired
    private UserService userService;

    /**
     * 页面跳转(制造404)
     */
    @RequestMapping("/{page}")
    public String showPage(@PathVariable String page, Model model) {
        // 测试页面传值
        model.addAttribute("msg", "tests涛涛涛涛涛涛");
        page = "user/" + page;
        System.out.println(page + "111");
        return page;
    }

    /**
     * error错误 算术异常
     */
    @RequestMapping("/error")
    public String error(User user) {
        int a = 100 / 0;
        return "ok";
    }

    /**
     * error错误 空指针异常
     */
    @RequestMapping("/error1")
    public String error1(User user) {
        String str = null;
        str.length();
        return "ok";
    }

    /**
     * 添加用户
     */
    @RequestMapping("/addUser")
    public String addUser(User user) {
        this.userService.addUser(user);
        return "ok";
    }


    /**
     * 查询用户列表(分页)
     */
    @RequestMapping("/list")
    public String showUsers(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "2") Integer pageSize, Model model) {
        PageInfo<User> list = this.userService.findUserByPage(pageNum, pageSize);
        model.addAttribute("list", list);

        return "user/list";
    }

    /**
     * 根据用户id查询用户
     */
    @RequestMapping("/findUserById")
    public String findUser(int id, Model model) {
        User user = this.userService.findUserById(id);
        model.addAttribute("user", user);
        return "user/edit";
    }

    /**
     * 修改用户
     */
    @RequestMapping("/edit")
    public String edit(@Valid User user, BindingResult result) {
        if (result.hasErrors()) {
            return "user/edit";
        }
        System.out.println(user);
        this.userService.updateUser(user);
        return "ok";
    }


    /**
     * 删除用户
     */
    @RequestMapping("/delete")
    public String delete(int id) {
        this.userService.deleteUserById(id);
        return "redirect:/user/list";
    }


}
